package com.nerve.android.cloudoffice.app.activity.assist;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.nerve.android.annotation.Acvitity;
import org.nerve.android.annotation.ViewOnId;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.R;
import com.nerve.android.cloudoffice.app.NavigationActivity;
import com.nerve.android.cloudoffice.app.activity.department.AddUserActivity;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.common.Reply;
import com.nerve.android.cloudoffice.common.Resource;
import com.nerve.android.cloudoffice.domain.User;
import com.nerve.android.cloudoffice.service.NetService;
import com.nerve.android.cloudoffice.service.data.DepartmentData;

@SuppressLint("HandlerLeak")
@Acvitity(layout=R.layout.activity_setting_user)
public class UserSettingActivity extends NavigationActivity implements OnClickListener{
	
	private User user;
	
	private String header;
	
	@ViewOnId(id=R.id.textView1)
	private TextView tipTV;
	
	@ViewOnId(id=R.id.name)
	private EditText nameET;
	@ViewOnId(id=R.id.header, clickListener="this")
	private ImageView headerIV;
	@ViewOnId(id=R.id.deparment_id)
	private EditText departmentET;
	@ViewOnId(id=R.id.position, clickListener="this")
	private EditText positionET;
	@ViewOnId(id=R.id.phone)
	public EditText phoneET;
	@ViewOnId(id=R.id.sex)
	private EditText sexET;
	@ViewOnId(id=R.id.address)
	public EditText addressET;
	@ViewOnId(id=R.id.birthday, clickListener="this")
	private EditText birthdayET;
	@ViewOnId(id=R.id.sign)
	private EditText signET;
	@ViewOnId(id=R.id.saleNumber)
	private EditText saleET;
	@ViewOnId(id=R.id.saleLayout)
	private LinearLayout saleLayout;
	
	private boolean isME;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			hideProgressDialog();
			switch (msg.what) {
			case WORKER_FAIL:
				toast(Const.ERROR);
				break;

			case WORKER_OK:
				//更新OfficeApplication中的User
				OfficeApplication.USER = user;
				toast("你的资料更新成功！");
				break;
			}
		}
	};
	
	@Override
	protected void initUI() {
		super.initUI();
		
		if(isME){
			customNavigateRightButton("保存个性", true);
			setNavTitle("我的资料");
		}else{
			setNavTitle(user.getName() + "的资料");
		}
		
		phoneET.setEnabled(isME);
		addressET.setEnabled(isME);
		signET.setEnabled(isME);
		tipTV.setVisibility(isME? View.VISIBLE:View.GONE);
		
		//如果不是销售部，隐藏销售额组件
		if(!OfficeApplication.isSaleManLogin())
			saleLayout.setVisibility(View.GONE);
		else
			saleLayout.setVisibility(View.VISIBLE);
		
		showUserInfo();
	}
	
	@Override
	protected void initData() {
		Object obj = getData(Const.SELECT_USER_ID, true);
		if(obj != null){
			user = (User)obj;
			isME = false;
		}else{
			user = OfficeApplication.USER;
			isME = true;
		}
		
		if(user == null){
			toast("没有登录，请重新登录");
			finish();
		}
	}
	
	private void showUserInfo(){
		nameET.setText(user.getName());
		headerIV.setImageResource(
				DepartmentData.getHeaderResource(user.getSex(), user.getHeader())
				);
		departmentET.setText(user.getDepartment().getName());
		positionET.setText(Resource.User.POSITION[user.getPosition()]);
		phoneET.setText(user.getCellPhone());
		sexET.setText(user.getSex() == User.MALE ?"男":"女");
		addressET.setText(user.getAddress());
		birthdayET.setText(user.getBirthday());
		signET.setText(user.getSign());
		
		header = user.getHeader();
	}
	
	@Override
	public void onClick(View v) {
		if(!isME)
			return ;
		
		switch(v.getId()){
		case R.id.birthday:
			showDialog(AddUserActivity.DATE_DIALOG);
			break;
		case R.id.header:
			Intent intent = new Intent(this, HeaderSelectActivity.class);
			intent.putExtra(HeaderSelectActivity.MALE, user.getSex() == User.MALE);
			
			startActivityForResult(intent, 1000);
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data == null)
			return ;
		
		String h = data.getStringExtra(HeaderSelectActivity.HEADER);
		header = h;
		
		headerIV.setImageResource(
				DepartmentData.getHeaderResource(user.getSex(), header)
				);
	}
	
	/**
     * 创建日期选择对话框
     */
    @Override
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog = null;
		switch (id) {
		case AddUserActivity.DATE_DIALOG:
			Calendar calendar = Calendar.getInstance();
			dialog = new DatePickerDialog(
					this,
					new DatePickerDialog.OnDateSetListener() {
						public void onDateSet(DatePicker dp, int year,
								int month, int dayOfMonth) {
							
							//设置日期
							birthdayET.setText( year + "-" + (month + 1) + "-"
									+ dayOfMonth);
						}
					}, 
					calendar.get(Calendar.YEAR), // 传入年份
					calendar.get(Calendar.MONTH), // 传入月份
					calendar.get(Calendar.DAY_OF_MONTH) // 传入天数
			);
			dialog.setTitle("选择日期");
			break;
		}
		return dialog;
    }
    
    @Override
    protected void onNavigateBackButtonClick() {
    	finish();
    }
    
    @Override
    protected void onNavigateRightButtonClick() {
    	user.setBirthday(getText(birthdayET));
    	user.setHeader(header);
    	user.setAddress(getText(addressET));
    	user.setCellPhone(getText(phoneET));
    	user.setSign(getText(signET));
    	user.setData1(saleET.getText().toString());
    	
    	showProgressDialog(null, "正在更新你的资料...");
    	new UpdateWorker().execute();
    }
    
    /**
     * @project: Cloudoffice_android
     * @file: UserSettingActivity.java
     * @package: com.nerve.android.cloudoffice.app.activity.assist
     * @description:
     *
     * @author: 集成显卡	1053214511@qq.com
    				IBM GDC, zengxm@cn.ibm.com
     * @date&time: Aug 25, 2013
     * @change log:
     */
    private class UpdateWorker extends AsyncTask<Void, Void, Integer>{

		@Override
		protected Integer doInBackground(Void... params) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("user.birthday", user.getBirthday());
			map.put("user.address", user.getAddress());
			map.put("user.header", user.getHeader());
			map.put("user.cellPhone", user.getCellPhone());
			map.put("user.sign", user.getSign());
			map.put("user.data1", user.getData1());
			
			Reply re = NetService.post(Const.HOST + "user/updateBatch.htm", map);
			if(re.isError()){
				Const.ERROR = re.getMessage().toString();
				return WORKER_FAIL;
			}
			
			return WORKER_OK;
		}
    	
		@Override
		protected void onPostExecute(Integer result) {
			handler.sendEmptyMessage(result);
		}
    }
}